
import React, { useEffect, useState, useRef } from 'react'
import { useNavigate } from 'react-router'

import { DatePicker, Table, Button, ConfigProvider, Modal, message } from 'antd';
import { Toast } from 'antd-mobile'
import { PlusCircleOutlined } from '@ant-design/icons';

// 引入中文语言包-日期选择器
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

//列
import { columns } from '../../constant/caseColumn.js'

import styles from './index.module.css'

//api
import { pushCase, getRecords } from '../../utils/axiosRequest/api'

function PushCase() {
  // 设置dayjs使用中文
  dayjs.locale('zh-cn');
  //消息提示
  const [messageApi, contextHolder] = message.useMessage();
  const [showDataSource, setDataSource] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [startDate, setStartDate] = useState('');
  const [startDateString, setStartDateString] = useState('');
  const [endDate, setEndDate] = useState('');
  const [endDateString, setEndDateString] = useState('');
  const [confirmLoading, setConfirmLoading] = useState(false);

  //[]空数组相当于componentDidMount
  useEffect(() => {
    queryTask()
    // 定时更新
    const timer = setInterval(queryTask, 5000);
    return () => {
      clearInterval(timer)
    }
  }, []);

  // 创建推送任务
  function createTask() {
    showCreateTaskModal()
  }

  //查询推送记录
  function queryTask() {
    const params = new Map()
    getRecords(params)
      .then(response => {
        const data = response.data
        hadleData(data)
      })
      .catch(error => {
        messageApi.open({ type: 'error', content: error.message });
      });
  }

  //处理数据
  function hadleData(data) {
    const taskList = data.data;
    const tempData = [];
    for (let i = 0; i < taskList.length; i++) {
      tempData.push({
        key: i,
        serial: i,
        pushId: taskList[i].pushId,
        creator: taskList[i].creator,
        createTime: taskList[i].createTime,
        status: taskList[i].status,
        pushRecords: taskList[i].pushRecords,
      })
    }
    //排序->根据更新时间排序
    tempData.sort((a, b) => b.createTime.localeCompare(a.createTime))
    //然后添加serial序号
    const dataWithSerial = tempData.map((item, index) => ({
      ...item,
      serial: index + 1  // 从1开始编号
    }));
    setDataSource(dataWithSerial)
  }

  // modal完全关闭后的回调
  function afterClose() {
    setStartDate('')
    setStartDateString('')
    setEndDate('')
    setEndDateString('')
  }

  const onChangeStartDate = (date, dateString) => {
    setStartDate(date)
    setStartDateString(dateString)
  };

  const onChangEndDate = (date, dateString) => {
    setEndDate(date)
    setEndDateString(dateString)
  };

  const showCreateTaskModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setConfirmLoading(true);
    const params = new Map()
    params.set('startTime', startDateString + ' 00:00:00')
    params.set('endTime', endDateString + ' 23:59:59')
    pushCase(params)
      .then(response => {
        setIsModalOpen(false);
        setConfirmLoading(false);
        const data = response.data
        if (data.code === '000') {
          Toast.show({ icon: 'success', content: '任务创建成功' })
        } else {
          messageApi.open({ type: 'error', content: data.des });
        }
      })
      .catch(error => {
        setIsModalOpen(false);
        setConfirmLoading(false);
        messageApi.open({ type: 'error', content: error.message });
      });
  };

  const handleCancel = () => {
    setConfirmLoading(false);
    setIsModalOpen(false);
  };

  return (
    <ConfigProvider locale={zhCN}>
      {contextHolder}
      <Modal
        confirmLoading={confirmLoading}
        afterClose={afterClose}
        cancelText={'取消推送'}
        okText={'开始推送'}
        title="创建任务"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <div className={styles.time_select_box}>
          <span>开始时间：</span>
          <DatePicker value={startDate} onChange={onChangeStartDate} placeholder={'选择开始时间'} />
          <span className={styles.end_time_title}>结束时间：</span>
          <DatePicker value={endDate} onChange={onChangEndDate} placeholder={'选择结束时间'} />
        </div>
      </Modal>
      <div className={styles.container}>
        <div className={styles.title_box}>
          <Button onClick={createTask} icon={<PlusCircleOutlined />} className={styles.template_padding}>创建任务</Button>
        </div>
        <div className={styles.data_box}>
          <Table bordered={true} columns={columns} dataSource={showDataSource} />
        </div>
      </div>
    </ConfigProvider>
  )
}

export default PushCase;